package com.example.demo.service.impl;

import com.example.demo.constant.MessageConstant;
import com.example.demo.exception.LoginFailedException;
import com.example.demo.exception.RegisterException;
import com.example.demo.mapper.AdminMapper;
import com.example.demo.pojo.PageResult;
import com.example.demo.pojo.dto.AdminLoginDTO;
import com.example.demo.pojo.dto.AdminPageDTO;
import com.example.demo.pojo.dto.AdminRegisterDTO;
import com.example.demo.pojo.entity.Admin;
import com.example.demo.service.AdminService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin login(AdminLoginDTO adminLoginDTO) {

        String username= adminLoginDTO.getUsername();
        String password=adminLoginDTO.getPassword();

        Admin admin=adminMapper.getByUsername(username);
        if(admin==null){
            throw new LoginFailedException(MessageConstant.ADMIN_UNEXIST);
        }

        password= DigestUtils.md5DigestAsHex(password.getBytes());
        if(!password.equals(admin.getPassword())){
            throw new LoginFailedException(MessageConstant.PASSWORD_ERROR);
        }

        return admin;
    }

    @Override
    public void register(AdminRegisterDTO adminRegisterDTO) {

        String username= adminRegisterDTO.getUsername();
        Admin adminDB=adminMapper.getByUsername(username);
        if(adminDB!=null){
            throw new RegisterException(MessageConstant.ADMIN_REGISTERED);
        }

        String password=adminRegisterDTO.getPassword();
        password= DigestUtils.md5DigestAsHex(password.getBytes());

        Admin admin = new Admin();
        BeanUtils.copyProperties(adminRegisterDTO,admin);
        admin.setPassword(password);
        admin.setCreateTime(LocalDateTime.now());
        adminMapper.insert(admin);
    }

    @Override
    public PageResult page(AdminPageDTO adminPageDTO) {
        PageHelper.startPage(adminPageDTO.getPage(), adminPageDTO.getPageSize());
        Page<Admin> page=adminMapper.list(adminPageDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void delete(Long id) {
        adminMapper.deleteById(id);
    }
}
